package com.ghxxzx.daglcustom.business_form.web;

import com.ghxxzx.daglcustom.business_form.domain.FormPo;
import com.ghxxzx.daglcustom.business_form.domain.dto.FormDto;
import com.ghxxzx.daglcustom.business_form.domain.dto.FormQuery;
import com.ghxxzx.daglcustom.business_form.service.Form2Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.tmsps.ne4spring.base.BaseAction;
import org.tmsps.ne4spring.base.ne.NePage;
import org.tmsps.ne4spring.utils.wrapper.WrapMapper;
import org.tmsps.ne4spring.utils.wrapper.Wrapper;

import javax.validation.Valid;
import java.text.ParseException;

@RestController
@RequestMapping("/form")
public class FormAction extends BaseAction {

	@Autowired
	private Form2Service formService;

	@GetMapping("/list")
	public Wrapper<NePage> list(@Valid FormQuery formQuery) {
		NePage page = formService.list(formQuery);
		return WrapMapper.ok(page);
	}

	@PostMapping("/add")
	public Wrapper<String> add(@Valid FormDto formDto) throws ParseException {
		FormPo formPo = new FormPo();
		formPo.setCode(formDto.getCode());
		formPo.setJson(formDto.getJson());
		formPo.setName(formDto.getName());
		formPo.setType_kid(formDto.getType_kid());
		bs.saveObj(formPo);
		return WrapMapper.ok("添加成功");
	}

	@PostMapping("/edit_form")
	public Wrapper<FormPo> editForm(@Valid String kid) {
		FormPo formPo = bs.findById(kid, FormPo.class);
		return WrapMapper.ok(formPo);
	}

	@PostMapping("/edit")
	public Wrapper<String> edit(@Valid FormDto formDto) throws ParseException {
		FormPo formPo = bs.findById(formDto.getKid(), FormPo.class);
		formPo.setName(formDto.getName());
		formPo.setCode(formDto.getCode());
		formPo.setJson(formDto.getJson());
		formPo.setJson_eval(formDto.getJson_eval());
		bs.updateObj(formPo);
		return WrapMapper.ok("修改成功");
	}

	@GetMapping("/delete")
	public Wrapper<String> delete(@Valid String kid) {
		bs.deleteById(kid, FormPo.class);
		return WrapMapper.ok("删除成功");
	}

	@GetMapping("/copy")
	public Wrapper<String> copy(@Valid String kid) {
		FormPo formPoSrc = bs.findById(kid, FormPo.class);
		FormPo formPo = new FormPo();
		formPo.setType_kid(formPoSrc.getType_kid());
		formPo.setName(formPoSrc.getName());
		formPo.setCode(formPoSrc.getCode() + "copy");
		formPo.setJson(formPoSrc.getJson());
		formPo.setWidget_json(formPoSrc.getWidget_json());
		formPo.setJson_eval(formPoSrc.getJson_eval());
		bs.saveObj(formPo);

		return WrapMapper.ok("复制成功");
	}

}
